package controller.services.impl;

import controller.services.PresetPersistenceService;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
import model.preset.Preset;
import model.preset.impl.PresetImpl;

public class PresetPersistenceServiceImpl implements PresetPersistenceService {

    private FileOutputStream saveFOS;
    private ObjectOutputStream saveOutputStream;

    private void openConnection() {
        try {
            saveFOS = new FileOutputStream("presetSave.vtpl");
            saveOutputStream = new ObjectOutputStream(saveFOS);

        } catch (FileNotFoundException ex) {
            Logger.getLogger(PlaylistPersistenceServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(PlaylistPersistenceServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    @Override
    public void saveData(Preset preset) {
        try {

            openConnection();
            saveOutputStream.writeObject(preset);
            // Close the file.
            saveOutputStream.close(); // This also closes saveFile.
            System.out.println("saved preset " + preset);

        } catch (IOException ex) {
            Logger.getLogger(PlaylistPersistenceServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    @Override
    public Preset readData() {
        File file = new File("presetSave.vtpl");
        if (file.exists() == false) {
            saveData(new PresetImpl());
        }

        try {
            FileInputStream fis = new FileInputStream("presetSave.vtpl");
            ObjectInputStream restore = new ObjectInputStream(fis);
            Preset preset = (Preset) restore.readObject();
            return preset;
        } catch (FileNotFoundException ex) {
            Logger.getLogger(PlaylistPersistenceServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException | ClassNotFoundException ex) {
            Logger.getLogger(PlaylistPersistenceServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }

}
